#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')

from django.shortcuts import render

# Create your views here.

from django.shortcuts import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.shortcuts import redirect

from appMonitor.models import EnvironmentName,Host,Runapp,Appport

import paramiko,os,time,datetime
from updataServerDataClass import updataServerDataClass

##不通过配置ssh.load_system_host_keys()本地known_hosts文件登陆[默认~/.ssh/known_hosts]
# 证书登陆
#hostname = '120.27.193.45'
username = 'yl'
sshPort = 7744
ylPassword = 'k@kd#$$0923*&Sd'  # yl帐号的密码 当使用sudo 执行命令时需要
rootPassword = 'oT2vpo#a4LWBv6CXV*St'  # root帐号密码
keyPath = r'S:\new_rsa\vm\yunlai_cjds_test'  # 私钥文件
keyPassword = 'PepjxU^qJ@oIsEI8$j9H'  # 私钥密码
paramiko.util.log_to_file('syslogin.log')  # 发送paramiko日志到syslogin.log文件

def index(request):
    envObj = EnvironmentName.objects.all().first()
    print 'envObj is:',envObj
    hostList = envObj.hosts.all()
    applicationList = hostList.first().runapps.all()
    # return HttpResponse('<h1>test appMonitor system !!!!</h1>')
    return render_to_response('appMonitor/index.html',
                              locals(),
                              context_instance=RequestContext(request))

def hostView(request,envID):
    print '传过来的环镜ID为:',envID
    envID = envID
    envObj = EnvironmentName.objects.get(id=envID)
    hostList = envObj.hosts.all()
    print hostList
    applicationList = hostList.first().runapps.all()
    return render_to_response('appMonitor/index.html',
                              locals(),
                              context_instance=RequestContext(request))

def applicationView(request,envID, hostID):
    print '传过来的环镜ID为:', envID
    print '传过来的主机ID为:',hostID
    envObj = EnvironmentName.objects.get(id=envID)
    hostList = envObj.hosts.all()
    print hostList

    hostObj = Host.objects.get(id=hostID)
    applicationList = hostObj.runapps.all()

    return render_to_response('appMonitor/index.html',
                                  locals(),
                                  context_instance=RequestContext(request))

def updataServerData(request,envID):
    print '传过来的环镜ID为:',envID
    envObj = EnvironmentName.objects.get(id=envID)
    hostList = envObj.hosts.all()
    print '些环镜下的所有主机:',hostList
    for host in hostList:
        print '主机为:',host.internetIP
        hostInternetIP = host.internetIP
        hostObj = Host.objects.update_or_create(internetIP=hostInternetIP)  # update_or_create不存在就创建记录，存在就不创建记录
        hostObj = Host.objects.get(internetIP=hostInternetIP)
        hostObj.runapps.clear()     #清除现有的主机与其之上运行的应用之间的关系(即第3 张表)
        updataServerDataObj = updataServerDataClass(hostname=hostInternetIP, username=username, sshPort=sshPort,
                                                    keyPath=keyPath, keyPassword=keyPassword,
                                                    usernameSudoPassword=ylPassword)
        for i in updataServerDataObj.getRunApp():
            print i['runApplicationName'], i['listenPort']
            for k, v in i.items():
                print '从服务器上获取到的数据清洗后的结果:', k, '===>', v

            appObj = Runapp.objects.update_or_create(appname = i['runApplicationName'])     # update_or_create不存在就创建记录，存在就不创建记录
            appObj = Runapp.objects.get(appname = i['runApplicationName'])
            appObj.ports.clear()    #清除应用与应用监听的端口之间的关系(即第3 张表)
            appObj.host_set.add(hostObj)    #重建应用与主机之间的关系
            appObj.save()

            if len(i['listenPort']) > 0:
                for port in i['listenPort']:
                    appPortObj = Appport.objects.update_or_create(port=port)  # update_or_create不存在就创建记录，存在就不创建记录
                    appPortObj = Appport.objects.get(port=port)
                    appPortObj.runapp_set.add(appObj)
                    appPortObj.save()

                    # appPortsGet = Appport.objects.get(port=port)
                    # appNameGet = Runapp.objects.get(appname=i['runApplicationName'])
                    # hostGet = Host.objects.get(internetIP=hostInternetIP)

                    # appNameGet.ports.clear()    #先删除关联关系再新建
                    # appNameGet.ports.add(appPortsGet)

                    # appNameGet.save()

                    # hostGet.runapps.clear()
                    # hostGet.runapps.add(appNameGet)
                    # hostGet.save()
            else:         #当应用没有监控端口时，端口默认为0
                appPortObj = Appport.objects.update_or_create(port=0)
                appPortObj = Appport.objects.get(port=0)
                appPortObj.runapp_set.add(appObj)
                appPortObj.save()
                # appName = Runapp.objects.update_or_create(appname=i['runApplicationName'])
                #
                # appPortsGet = Appport.objects.get(port=0)
                # appNameGet = Runapp.objects.get(appname=i['runApplicationName'])
                # hostGet = Host.objects.get(internetIP=hostInternetIP)
                # appNameGet.ports.clear()        #先删除关联关系再新建
                # appNameGet.ports.add(appPortsGet)
                # appNameGet.save()
                #
                # # hostGet.runapps.clear()
                # hostGet.runapps.add(appNameGet)
                # hostGet.save()


    return redirect('appMonitor:index')
    # return HttpResponse('<h1>刷新后台数据成功！</h1>')


def appDetail(request,appID):
    pass
    return render_to_response('appMonitor/index.html',
                              locals(),
                              context_instance=RequestContext(request))


def allEnvAppDiff(request):
    appList = Runapp.objects.exclude(appname='base-web-admin.jar').all()
    print appList
    return render_to_response('appMonitor/allEnvAppDiff.html',
                              locals(),
                              context_instance=RequestContext(request))

